package com.yc.web.servlets.admin;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.yc.bean.Cust1;
import com.yc.bean.User;
import com.yc.bean.tb_user;
import com.yc.model.JsonModel;
import com.yc.utils.EncryptUtils;
import com.yc.web.servlets.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zwei
 * @create 2024-06-19 20:00
 */
@WebServlet("/admin/adminUser.action")
@MultipartConfig
public class AdminUserServlet extends BaseServlet {
    // OSS 配置信息
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // OSS 外网节点或自定义域名
    private static final String accessKeyId = "LTAI5tMaMpqNrQHS5ums69Mr";
    private static final String accessKeySecret = "qrCGpsNCirvOSM8wrhnj97hSMO41qw";
    private static final String bucketName = "daiwei001";
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchAlgorithmException, IOException, ServletException {
        // 获取上传的文件
        Part filePart = req.getPart("file");
        String fileName = filePart.getSubmittedFileName();
        JsonModel jm=new JsonModel();
        if (fileName==null){
            jm.setCode(0);
            jm.setError("请选择图片");
            super.writeJson(jm,resp);
            return;
        }
        InputStream fileContent = filePart.getInputStream();
        // 生成唯一的文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String objectName = uuid + "_" + fileName;
        System.out.println(objectName);
        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(filePart.getSize());
        ossClient.putObject(bucketName, objectName, fileContent, metadata);
        ossClient.shutdown();
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        System.out.println(url);
//        HttpSession session=req.getSession();
//        session.setAttribute("url",url);

        tb_user user=super.parseObjectFromRequest(req,tb_user.class);

        if (user.getTel()==null&&user.getPwd()==null&&user.getAvatar()==null&&user.getUsername()==null){
            jm.setCode(0);
            jm.setError("请补充数据");
            super.writeJson(jm,resp);
            return;
        }
        String sql="insert into tb_user( username,pwd,avatar,nickname,tel,create_date,disabled) values(?,?,?,?,?,?,?)";
        int result=dbHelper.doUpdate(sql,user.getUsername(),user.getPwd(),url,user.getNickname(),user.getTel(),LocalDateTime.now(),0);
        jm.setCode(1);
        super.writeJson(jm,resp);
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchAlgorithmException, IOException {
        String username = req.getParameter("username");
        String pwd = EncryptUtils.encryptToMD5(EncryptUtils.encryptToMD5(req.getParameter("password")));
        String sql = "select * from cust where name=? and pwd=?";
        List<Map<String, Object>> list = dbHelper.select(sql, username, pwd);
        Map<String, Object> map = new HashMap<>();
        if (list.isEmpty()) {
            map.put("code", 1);
            map.put("msg", "用户名或者密码错误");
            super.writeObjectToJson(map, resp);
            return;
        }
        HttpSession session = req.getSession();
        session.setAttribute("admin", username);
        map.put("code", 0);
        map.put("msg", "登陆成功");
        super.writeObjectToJson(map, resp);
    }

    public void stopUser(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        Map<String, Object> map = new HashMap<>();
        String id = req.getParameter("idsStr");
        String[] parts = id.split(",");
        String sql = "update tb_user set disabled=? where id=?";
        for (String str : parts) {
            dbHelper.doUpdate(sql, 1, str);
        }
        map.put("code", 0);
        map.put("msg", "修改成功");
        super.writeObjectToJson(map, resp);
    }

    public void startUser(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        Map<String, Object> map = new HashMap<>();
        String id = req.getParameter("idsStr");
        String[] parts = id.split(",");
        String sql = "update tb_user set disabled=? where id=?";
        for (String str : parts) {
            dbHelper.doUpdate(sql, 0, str);
        }
        map.put("code", 0);
        map.put("msg", "修改成功");
        super.writeObjectToJson(map, resp);
    }

    public void delete1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("idsStr");
        String[] parts = id.split(",");
        String sql = "delete from tb_user where id=?";
        for (String str : parts) {
            dbHelper.doUpdate(sql, str);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "删除用户成功");
        super.writeObjectToJson(map, resp);
    }



    public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchAlgorithmException, IOException {
        Map<String, Object> map = new HashMap<>();
        tb_user user = super.parseObjectFromRequest(req, tb_user.class);
        user.setPwd(EncryptUtils.encryptToMD5(EncryptUtils.encryptToMD5(user.getPwd())));
        String sql = "update tb_user set nickname=?,pwd=?,tel=? where username =?";
        int result = dbHelper.doUpdate(sql, user.getNickname(), user.getPwd(), user.getTel(),user.getUsername());
        if (result > 0) {
            map.put("code", 0);
            map.put("msg", "更新用户成功");
        } else {
            map.put("code", 1);
            map.put("msg", "更新用户失败");
        }
        super.writeObjectToJson(map, resp);
    }

    public void delUser(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        tb_user user = super.parseObjectFromRequest(req, tb_user.class);
        String sql = "delete from tb_user where id=?";
        int r = dbHelper.doUpdate(sql, user.getId());
        Map<String, Object> map = new HashMap<>();
        if (r > 0) {
            map.put("code", 0);
            map.put("msg", "删除用户成功");
            resp.setStatus(200);
        } else {
            resp.setStatus(500);
            map.put("code", 1);
            map.put("msg", "删除失败");
        }
        super.writeObjectToJson(map, resp);
    }

    public void findAllUser(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        tb_user user = super.parseObjectFromRequest(req, tb_user.class);
        int page = 1;
        if (req.getParameter("page") != null) {
            page = Integer.parseInt(req.getParameter("page"));
        }
        int limit = 10;
        if (req.getParameter("limit") != null) {
            limit = Integer.parseInt(req.getParameter("limit"));
        }
        String sql1 = "select*from tb_user where 1=1 ";
        String sql2 = "select count(*) as total from tb_user where 1=1 ";
        int skip = (page - 1) * limit;
        List<Object> params = new ArrayList<>();
        if (user.getId() != null) {
            sql1 += " and id=? ";
            sql2 += " and id=? ";
            params.add(user.getId());
        }
        if (user.getUsername() != null && !"".equals(user.getUsername())) {
            sql1 += " and username like '%" + user.getUsername() + "%'  ";
            sql2 += " and username like '%" + user.getUsername() + "%'  ";
        }
        List<tb_user> list = dbHelper.select(tb_user.class, sql1 + " order by create_date DESC  limit " + limit + " offset " + skip, params.toArray());
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> result = dbHelper.select(sql2, params.toArray());
        int total = Integer.parseInt(result.get(0).get("total").toString());
        map.put("code", 0);
        map.put("msg", "查询用户成功");
        map.put("count", total);
        map.put("data", list);
        super.writeObjectToJson(map, resp);
    }
}
